﻿using System;
using System.Collections.Generic;
using System.Text;
using MP.Core.Config;
using MP.Core.Library;
using MP.Core.Authentication.Entity;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace MP.Core.Authentication.Control
{
    public class AuthenBase : System.Web.UI.UserControl
    {
        #region "Variable"
        public RoleAction roleAction;
        private DepartConfig globalConfig = null;
        public DepartConfig Config
        {
            get
            {
                if (globalConfig == null)
                    throw (new Exception("Chưa load dữ liệu config"));
                return globalConfig;
            }
        }

        /// <summary>
        /// Load cac config cho ung dung theo phong ban va chi nhanh cua user
        /// </summary>
        public void LoadSystemParamConfig()
        {
            
            LoadSystemParamConfig(BranchId, DepartId);
        }
        /// <summary>
        /// Load lai cac gia tri config cho ung dung theo phong ban va chi nhanh.
        /// </summary>
        /// <param name="BranchID"></param>
        /// <param name="DepartID"></param>
        public string LoadSystemParamConfig(Guid BranchID, Guid DepartmentID)
        {
            globalConfig = new DepartConfig();
            Logger log = new Logger("MP.Core.Authentication.Control");
            log.Start("LoadSystemParam");
            String sql = @"SELECT * 
                            FROM maSystemParam
                            WHERE IsEnabled=1 ";
            //if(DepartId == Guid.Empty)
            //   sql += @" AND(  DepartID IS NULL AND BranchID = @BranchID)";
            //if (DepartId != Guid.Empty)
                sql += @" AND( (Region='DEPT' AND BranchID = @BranchID AND DepartID = @DepartID)
                                    OR ( Region='BRANCH' AND BranchID = @BranchID)
                                    ) ";
                        
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@BranchID", BranchID);
            param[1] = new SqlParameter("@DepartID", DepartmentID);
            DataTable tblConfig = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.Text, sql, param);
            String columnName = "ParamName";
            String valueName = "ParamValue";
            try
            {
                //lay cac config rieng cho tung phong ban
                if (DepartmentID != Guid.Empty)
                {
                    
                    Config.AS_MINUTE_FOR_LATE = int.Parse(SelectValue(tblConfig, columnName, valueName, "AS_MINUTE_FOR_LATE"));
                    Config.AS_CAN_LOG_ON_BEFORE_MINUTES = int.Parse(SelectValue(tblConfig, columnName, valueName, "AS_CAN_LOG_ON_BEFORE_MINUTES"));
                    Config.AS_CAN_LOG_OFF_AFTER_MINUTES = int.Parse(SelectValue(tblConfig, columnName, valueName, "AS_CAN_LOG_OFF_AFTER_MINUTES"));
                    Config.AS_CAN_TRANSFER_AFTER_NOT_COMMIT = SelectValue(tblConfig, columnName, valueName, "AS_CAN_TRANSFER_AFTER_NOT_COMMIT").ToUpper() == "Y";
                    Config.AS_IS_USE_AGENT_LOGIN = SelectValue(tblConfig, columnName, valueName, "AS_IS_USE_AGENT_LOGIN").ToUpper() == "Y";
                    Config.AS_MINUTE_FOR_ABSENT = int.Parse(SelectValue(tblConfig, columnName, valueName, "AS_MINUTE_FOR_ABSENT"));
                    Config.AS_TRANSFER_LIMIT_NUM = int.Parse(SelectValue(tblConfig, columnName, valueName, "AS_TRANSFER_LIMIT_NUM"));
                    log.Debug("AS_TRANSFER_LIMIT_NUM:" + Config.AS_TRANSFER_LIMIT_NUM);
                    //Config.SQ_NM = (double)FNumber.ConvertDecimal(SelectValue(tblConfig, columnName, valueName, "SQ_NM"));

                  
                }
                else
                {
                    log.Debug("DepartId null. Khong load config cua phong ban");
                }
                //lay cac config rieng cho tung chi nhanh
                //else
                //{
                Config.CT_ORDER_BEFORE_DAYS = int.Parse(SelectValue(tblConfig, columnName, valueName, "CT_ORDER_BEFORE_DAYS"));
                Config.CT_ORDER_MAX_NUMBER_OF_RATION_ONE_MEAL = int.Parse(SelectValue(tblConfig, columnName, valueName, "CT_ORDER_MAX_NUMBER_OF_PORTIONS_ONE_MEAL"));
                Config.CT_ORDER_MORE_THAN_ONE_MEAL = SelectValue(tblConfig, columnName, valueName, "CT_ORDER_MORE_THAN_ONE_MEAL").ToUpper() == "Y";
                Config.CT_HAS_2_MEAL_ONE_DAY = SelectValue(tblConfig, columnName, valueName, "CT_HAS_2_MEAL_ONE_DAY").ToUpper() == "Y";

                // param giam sat chat luong
                Config.SQ_ROUND = int.Parse(SelectValue(tblConfig, columnName, valueName, "SQ_ROUND"));

                Config.SYS_RECORDS_PER_PAGE = int.Parse(SelectValue(tblConfig, columnName, valueName, "SYS_RECORDS_PER_PAGE"));
                //}
            }
            catch (Exception ex)
            { 
                log.Error(ex.ToString());
                return ex.ToString();
            }
            log.End("LoadSystemParam");
            return "";
        }
       
        /// <summary>
        /// Kiem tra account nay co quyen tren record khong
        /// </summary>
        /// <param name="tableName">Ten table</param>
        /// <param name="recordID">ID cua record. Neu truyen Guid.Empty thi co quyen tao tac.</param>
        /// <param name="accountID">Account doanh nghiep dang nhap</param>
        /// <returns>
        ///     True: Co quyen thao tac
        ///     False: Khong co quyen thao tac
        /// </returns>
        public bool CheckRoleInRecord(string tableName, Guid recordID, Guid accountID)
        {
            log.Debug("CheckRoleInRecord");
            log.Param("tableName",tableName);
            log.Param("recordID",recordID);
            log.Param("accountID", accountID);
            if (roleAction.IsEditToUser)
            {
                log.Warning("record co quyen edit");
                return true;
            }
            if (recordID == null || recordID == Guid.Empty)
            {
                log.Warning("RecordID null");
                return true;
            }
            string sql = "SELECT * FROM " + tableName + " WHERE ID ='" + recordID + "'";
            DataTable tbl = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS,CommandType.Text, sql);
            if (tbl == null || tbl.Rows.Count == 0)
            {
                log.Warning("Khong tim thay record");
                return false;
            }
            if (!tbl.Columns.Contains("RecordOfAccount"))
            {
                log.Warning("Khong tim thay column account");
                return true;
            }
            log.Param("RecordOfAccount", tbl.Rows[0]["RecordOfAccount"].ToString());
            return tbl.Rows[0]["RecordOfAccount"].ToString() == accountID.ToString();
        }
        public static string SelectValue(DataTable tblSource, String lookupColumn, String valueColumn, String findString)
        {
            DataRow[] r = tblSource.Select(lookupColumn + "='" + findString + "'");
            return r.Length == 0 ? null : r[0][valueColumn].ToString();

        }
        //{
        //    get
        //    {
        //        object obj = ViewState["roleAction"];
        //        if (obj != null) 
        //            return (RoleAction)obj;
        //        return new RoleAction();
        //    }
        //    set { ViewState["roleAction"] = value; }
        //}

        public RoleAction roleFullAdmin;
        //{
        //    get { return ViewState["roleFullAdmin"] != null ? (RoleAction)ViewState["roleFullAdmin"] : new RoleAction(); }
        //    set { ViewState["roleFullAdmin"] = value; }
        //}

        private Hashtable userCheck
        {
            get { return ViewState["userCheck"] != null ? (Hashtable)ViewState["userCheck"] : new Hashtable(); }
            set { ViewState["userCheck"] = value; }
        }

        protected Logger log;

        public string ModuleID
        {
            get { return ViewState["ModuleID"] != null ? ViewState["ModuleID"].ToString() : ""; }
            set { ViewState["ModuleID"] = value; }
        }

        public string MenuParentId
        {
            get { return ViewState["MenuParentId"] != null ? ViewState["MenuParentId"].ToString() : ""; }
            set { ViewState["MenuParentId"] = value; }
        }

        public string MenuRootId
        {
            get { return ViewState["MenuRootId"] != null ? ViewState["MenuRootId"].ToString() : ""; }
            set { ViewState["MenuRootId"] = value; }

        }

        /// <summary>
        /// Chuc vu cua nhan vien --> tu database
        /// </summary>
        public Guid mJobId
        {
            get { return ViewState["mJobId"] != null ? !string.IsNullOrEmpty(ViewState["mJobId"].ToString()) ? Util.IsGuid(ViewState["mJobId"].ToString()) ? new Guid(ViewState["mJobId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["mJobId"] = value; }
        }

        /// <summary>
        /// Phong cua nhan vien --> tu database
        /// </summary>
        public Guid mDepartId
        {
            get { return ViewState["mDepartId"] != null ? !string.IsNullOrEmpty(ViewState["mDepartId"].ToString()) ? Util.IsGuid(ViewState["mDepartId"].ToString()) ? new Guid(ViewState["mDepartId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["mDepartId"] = value; }
        }

        /// <summary>
        /// Chi nhanh cua nhan vien --> tu database
        /// </summary>
        public Guid mBranchId
        {
            get { return ViewState["mBranchId"] != null ? !string.IsNullOrEmpty(ViewState["mBranchId"].ToString()) ? Util.IsGuid(ViewState["mBranchId"].ToString()) ? new Guid(ViewState["mBranchId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["mBranchId"] = value; }
        }

        public Guid mEmployeeId
        {
            get { return ViewState["mEmployeeId"] != null ? !string.IsNullOrEmpty(ViewState["mEmployeeId"].ToString()) ? Util.IsGuid(ViewState["mEmployeeId"].ToString()) ? new Guid(ViewState["mEmployeeId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["mEmployeeId"] = value; }
        }

        /// <summary>
        /// Phong ban chon ngoai giao dien
        /// </summary>
        public Guid DepartId
        {
            get { return ViewState["DepartId"] != null ? !string.IsNullOrEmpty(ViewState["DepartId"].ToString()) ? Util.IsGuid(ViewState["DepartId"].ToString()) ? new Guid(ViewState["DepartId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["DepartId"] = value; }
        }

        public Guid BranchId
        {
            get { return ViewState["cBranchId"] != null ? !string.IsNullOrEmpty(ViewState["cBranchId"].ToString()) ? Util.IsGuid(ViewState["cBranchId"].ToString()) ? new Guid(ViewState["cBranchId"].ToString()) : Guid.Empty : Guid.Empty : Guid.Empty; }
            set { ViewState["cBranchId"] = value; }
        }

        #endregion

        #region "Override Method"
        protected override void OnLoad(EventArgs e)
        {
            log = new Logger(this.GetType());
            //if (!IsPostBack)
            //{
            userCheck = new Hashtable();
            if (string.IsNullOrEmpty(Util.CurrentUserName))
            {
                this.Visible = false;
                return;
            }
            else
            {
                roleFullAdmin = GetRoleAction(EnumModules.FULL_ADMIN);
            }
            //}
            
            ModuleID = GetModuleId();
            InitAuthen(ModuleID);

            if (!string.IsNullOrEmpty(MenuRootId))
            {
                CookieManager.setCookie(Page, "slidemenu", MenuRootId);
            }

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Util.CurrentUserName))
                {
                    DataTable tbl = GetProfiles();
                    if (tbl != null && tbl.Rows.Count > 0)
                    {
                        if (!Convert.IsDBNull(tbl.Rows[0]["BranchId"]) && !string.IsNullOrEmpty(tbl.Rows[0]["BranchId"].ToString()))
                            mBranchId = new Guid(tbl.Rows[0]["BranchId"].ToString());
                        if (!Convert.IsDBNull(tbl.Rows[0]["DepartId"]) && !string.IsNullOrEmpty(tbl.Rows[0]["DepartId"].ToString()))
                            mDepartId = new Guid(tbl.Rows[0]["DepartId"].ToString());
                        if (!Convert.IsDBNull(tbl.Rows[0]["JobId"]) && !string.IsNullOrEmpty(tbl.Rows[0]["JobId"].ToString()))
                            mJobId = new Guid(tbl.Rows[0]["JobId"].ToString());
                    }
                }
            }

            if (BranchId == Guid.Empty)
            {
                BranchId = FGuid.ToGuid(CookieManager.getCookie(Page, "cBranchId"));
            }

            base.OnLoad(e);

        }
        #endregion

        #region "Public Method"

        public void InitAuthen(string Module)
        {
            if (Module == ".")
                return;

            ModuleID = Module;
            if (roleAction == null && !string.IsNullOrEmpty(ModuleID))
            {
                roleAction = GetRoleAction(ModuleID);
                DepartId = GetDepartId(ModuleID);

                UpdateModule();
            }

            if (!((roleFullAdmin != null && roleFullAdmin.IsShow) || (roleAction != null && roleAction.IsShow)))
            {
                RedirectLogin();
            }
        }

        public bool CheckRoles(string Action)
        {
            return CheckRoles(ModuleID, Action);
        }

        public bool CheckRoles(string Module, string Action)
        {
            return MPRoleProvider.CreateInstant().CheckRoles(Util.CurrentUserName, Module, Action);
        }

        public RoleAction GetRoleAction(string Module)
        {
            RoleAction r = MPRoleProvider.CreateInstant().GetRoleAction(Util.CurrentUserName, Module);
            if (r != null)
                r.UpdateFields();
            return r;
        }

        public bool IsAction(string Action)
        {
            if (roleAction == null) return false;
            if (!roleAction.Items.ContainsKey(Action))
                return false;
            return Convert.ToBoolean(roleAction.Items[Action]);
        }

        public void RedirectLogin()
        {
                Response.Redirect(EnumAuthentication.PageRedirect + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
        }

        public void RefreshPage()
        {
            Response.Redirect(Request.RawUrl);
        }

        public string PreviousPage()
        {
            return Request.UrlReferrer.AbsolutePath;
        }

        public string PreviousPageParam()
        {
            return Request.UrlReferrer.PathAndQuery;
        }

        public void RedirectPage(params string[] param)
        {
            Response.Redirect(Request.Url.AbsolutePath + "?" + string.Join("&", param));
        }
        //-------------------------
        #region Permission
        public bool IsShow()
        {
            return IsAction(EnumActions.SHOW);
        }

        public bool IsShow(Guid branchId, Guid departId)
        {
            if (roleAction == null) return false;
            if (roleAction.IsShow)
                return true;
            if (branchId == mBranchId && departId == mDepartId)
                return true;
            return false;
        }
        /// <summary>
        /// Xem nguoi nay co quyen xem cua nguoi khac hay khong
        /// </summary>
        /// <returns></returns>
        public bool IsShowForce()
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra co toan quyen Edit hay ko
            if (roleFullAdmin != null && (roleFullAdmin.IsShow || roleFullAdmin.IsEditToUser))
            {
                return true;
            }

            return roleAction.IsEditToUser;
        }
        public bool IsShowForce(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra co toan quyen Edit hay ko
            if (roleFullAdmin != null && (roleFullAdmin.IsShow || roleFullAdmin.IsShowToUser))
            {
                return true;
            }

            if (roleAction.IsShowToUser) // Có quyền edit thông tin của người khác
            {
                if (Util.CurrentUserName != toUser)
                {
                    int level = -1;
                    if (userCheck[toUser] != null)
                        level = (int)userCheck[toUser];
                    else
                    {
                        level = MPRoleProvider.CreateInstant().ComparePriority(Util.CurrentUserName, toUser);
                        userCheck[toUser] = level;
                    }

                    if (level > 0)
                        f = true;
                    else
                        f = false;
                }
                else
                {
                    f = true;
                }
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsShow && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }

        public bool IsAdd()
        {
            return IsAction(EnumActions.ADD);
        }

        public bool IsEdit()
        {
            return IsAction(EnumActions.EDIT);
        }

        /// <summary>
        /// Kiểm tra xem có quyền sửa thông tin của người khác không
        /// </summary>
        /// <param name="toUser">User kiểm tra</param>
        /// <returns></returns>
        public bool IsEdit(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;
            if (roleAction.IsEditToUser) // Có quyền edit thông tin của người khác
            {
                f = true;
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsEdit && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }

        public bool IsEdit(Guid branchId, Guid departId)
        {
            if (roleAction == null) return false;
            bool f = false;
            if (roleAction.IsEditToUser) // Có quyền edit thông tin của người khác
            {
                f = true;
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsEdit && branchId == mBranchId && departId == mDepartId)
                    f = true;
            }
            return f;
        }

        public bool IsEditForce()
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra co toan quyen Edit hay ko
            if (roleFullAdmin != null && (roleFullAdmin.IsEdit || roleFullAdmin.IsEditToUser))
            {
                return true;
            }

            return roleAction.IsEditToUser;
        }

        /// <summary>
        /// Kiểm tra xem có quyền sửa thông tin của người khác không
        /// Kiểm tra thêm cấp bậc nhân viên
        /// </summary>
        /// <param name="toUser">User kiểm tra</param>
        /// <returns></returns>
        public bool IsEditForce(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra co toan quyen Edit hay ko
            if (roleFullAdmin != null && (roleFullAdmin.IsEdit || roleFullAdmin.IsEditToUser))
            {
                return true;
            }

            if (roleAction.IsEditToUser) // Có quyền edit thông tin của người khác
            {
                if (Util.CurrentUserName != toUser)
                {
                    int level = -1;
                    if (userCheck[toUser] != null)
                        level = (int)userCheck[toUser];
                    else
                    {
                        level = MPRoleProvider.CreateInstant().ComparePriority(Util.CurrentUserName, toUser);
                        userCheck[toUser] = level;
                    }

                    if (level > 0)
                        f = true;
                    else
                        f = false;
                }
                else
                {
                    f = true;
                }
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsEdit && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }

        public bool IsDelete()
        {
            return IsAction(EnumActions.DELETE);
        }

        /// <summary>
        /// Kiểm tra xem có quyền xóa thông tin của người khác không
        /// </summary>
        /// <param name="toUser">User kiểm tra</param>
        /// <returns></returns>
        public bool IsDelete(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;
            if (roleAction.IsDeleteToUser)
            {
                f = true;
            }
            else
            {
                if (roleAction.IsDelete && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }

        public bool IsDelete(Guid branchId, Guid departId)
        {
            if (roleAction == null) return false;
            bool f = false;
            if (roleAction.IsDeleteToUser)
            {
                f = true;
            }
            else
            {
                if (roleAction.IsDelete && branchId == mBranchId && departId == mDepartId)
                    f = true;
            }
            return f;
        }

        public bool IsDeletedForce(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra toan quyen he thong
            if (roleFullAdmin != null && (roleFullAdmin.IsDelete || roleFullAdmin.IsDeleteToUser))
            {
                return true;
            }

            if (roleAction.IsDeleteToUser) // Có quyền edit thông tin của người khác
            {
                if (Util.CurrentUserName != toUser)
                {
                    int level = -1;
                    if (userCheck[toUser] != null)
                        level = (int)userCheck[toUser];
                    else
                    {
                        level = MPRoleProvider.CreateInstant().ComparePriority(Util.CurrentUserName, toUser);
                        userCheck[toUser] = level;
                    }

                    if (level > 0)
                        f = true;
                    else
                        f = false;
                }
                else
                {
                    f = true;
                }
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsDelete && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }

        public bool IsEnable()
        {
            return IsAction(EnumActions.ENABLE);
        }

        public bool IsDisable()
        {
            return IsAction(EnumActions.DISABLE);
        }

        public bool IsEnableForce(string toUser)
        {
            if (roleAction == null) return false;
            bool f = false;

            // Kiem tra toan quyen he thong
            if (roleFullAdmin != null && (roleFullAdmin.IsEnable))
            {
                return true;
            }

            if (roleAction.IsEnable) // Có quyền edit thông tin của người khác
            {
                if (Util.CurrentUserName != toUser)
                {
                    int level = -1;
                    if (userCheck[toUser] != null)
                        level = (int)userCheck[toUser];
                    else
                    {
                        level = MPRoleProvider.CreateInstant().ComparePriority(Util.CurrentUserName, toUser);
                        userCheck[toUser] = level;
                    }

                    if (level > 0)
                        f = true;
                    else
                        f = false;
                }
                else
                {
                    f = true;
                }
            }
            else // không có quyền edit thông tin người khác
            {
                if (roleAction.IsEnable && Util.CurrentUserName == toUser)
                    f = true;
            }
            return f;
        }
        /// <summary>
        /// Co quyen add tren record
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public bool IsAdd(string tableName, string recordId)
        {
            return IsAdd();
        }
        /// <summary>
        /// Co quyen edit tren record
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public bool IsEdit(string tableName, string recordId)
        {
            return IsEdit();
        }
        /// <summary>
        /// Co quyen xem tren record
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public bool IsShow(string tableName, string recordId)
        {
            return IsShow();
        }
        /// <summary>
        /// Co quyen delete tren record
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        public bool IsDelete(string tableName, string recordId)
        {
            return IsDelete();
        }

        #endregion

        public Guid GetDepartId(string moduleId)
        {
            string strSQL = "Select * " +
                            "From mbModules " +
                            "Where ModCode=@ModCode";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@ModCode", moduleId);
            DataTable tbl = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL, param);
            if (tbl != null && tbl.Rows.Count > 0)
            {
                if (!Convert.IsDBNull(tbl.Rows[0]["DepartId"]))
                {
                    return new Guid(tbl.Rows[0]["DepartId"].ToString());
                }
            }
            return Guid.Empty;
        }

        /// <summary>
        /// Luu cac gia tri cua user vao session
        /// </summary>
        /// <returns></returns>
        public UserSession UserSession
        {
            get
            {
                if (Session["UserSession"] == null)
                    SetUserSession();
                return (UserSession)Session["UserSession"];
            }

        }
        /// <summary>
        /// Lay cac thiet dat cua user trong session
        /// </summary>
        /// <returns></returns>
        protected void SetUserSession()
        {
            Session["UserSession"] = new UserSession(Session.SessionID, Page);

        }

        /// <summary>
        /// Lay doi tuong ghi log
        /// </summary>
        public Logger Log
        {
            get { return log; }
        }

        public int PageIndex()
        {
            return PageIndex("page", GlobalConfig.SYS_RECORDS_PER_PAGE);
        }


        public int PageIndex(string page, int RowInPage)
        {
            int p = 0;

            if (!string.IsNullOrEmpty(Request["page"]))
                int.TryParse(Request["page"], out p);
            if (p <= 0)
                p = 1;
            return (p - 1) * RowInPage;
        }

        #endregion

        #region "Private Method"
        string GetModuleId()
        {
            string id = this.GetType().ToString();
            string strSQL = "PRC_GetModuleControl";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@controlId", id);
            DataTable tbl = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
            if (tbl != null && tbl.Rows.Count > 0)
            {
                MenuParentId = tbl.Rows[0]["MenuParentId"].ToString();
                MenuRootId = tbl.Rows[0]["MenuRootId"].ToString();
                return tbl.Rows[0]["ModCode"].ToString();
            }
            MenuParentId = "";
            return "";
        }

        void UpdateModule()
        {
            string strSQL = "Update mbUserControl " +
                            "Set ModCode=@ModCode " +
                            "Where ControlId=@ControlId";
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@ModCode", ModuleID);
            param[1] = new SqlParameter("@ControlId", this.GetType().ToString());
            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL, param);
        }

        DataTable GetProfiles()
        {
            string strSQL = "Hr_Profiles";
            SqlParameter param = new SqlParameter("@username", Util.CurrentUserName);
            return SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
        }
        #endregion
    }
}
